package org.oep.widgets;

import javax.microedition.lcdui.Font;

public class Utils {
	public static String [] tokenize(String s) {
		return tokenize(s, ' ');
	}
	
	public static String [] tokenize(String s, char delimiter) {
		int spaceCount = 0;
		for(int i = 0; i < s.length(); i++)
			if(s.charAt(i) == delimiter) spaceCount++;
		String [] tokens = new String [spaceCount + 1];
		String tmp = new String();
		int index = 0;
		for(int i = 0; i < s.length(); i++) {
			if(s.charAt(i) != delimiter)
				tmp += s.charAt(i);
			else {
				tokens[index] = tmp;
				tmp = "";
				index++;
			}
		}
		tokens[ tokens.length - 1 ] = tmp;
		return tokens;
	}
	
	public static String [] addLineBreaks(String s, Font f, int width) {
		String [] tokens = Utils.tokenize(s);
		return Utils.addLineBreaks(tokens, f, width);
	}
	
	public static String [] addLineBreaks(String [] tokens, Font f, int width) {
		String tmp = new String();
		String [] lines = new String[1];
		
		if(tokens.length == 0) return lines;
		else if(tokens.length == 1) return tokens;
		
		lines[0] = tokens[0];
		
		int currentLine = 0;
		for(int i = 1; i < tokens.length; i++) {
			tmp = lines[currentLine] + " " + tokens[i];
			
			// If we don't violate the width, we just add it to this line
			if(f.charsWidth(tmp.toCharArray(), 0, tmp.length()) < width) {
				lines[currentLine] = tmp;
			}
			// If we do violate the width, we just tack it on the next line
			else {
				String [] l = lines;
				lines = new String[currentLine + 2];
				currentLine++;
				
				
				for(int j = 0; j < l.length; j++) {
					lines[j] = l[j];
				}
				
				lines[currentLine] = tokens[i];
			}
		}
		
		return lines;
	}
}
